<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Interactive Web Console</title>
    <!-- <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/xterm/5.5.0/xterm.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/xterm/5.5.0/xterm.js"></script> -->
	 <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
     <script src="./node_modules/xterm/lib/xterm.js"></script>
<!--     <script src="./node_modules/xterm-addon-fit/lib/xterm-addon-fit.js"></script>-->
<!--     <script src="./node_modules/xterm-addon-attach/lib/xterm-addon-attach.js"></script>-->
</head>
<body>
    <div id="terminal" style="width: 1200px; height: 960px;"></div>
    <script>
        // Terminal
        var terminal = new Terminal({
            cursorBlink: true,
            cursorStyle: "underline", //光标样式
            convertEol: true
        });
        terminal.open(document.getElementById('terminal'));

		const termSymbol = '\x1B[1;3;31m $ \x1B[0m';

		const clientId = 'Q2LnhojsDN7koghqVLoOxRotx9SYRhqP';
		const subProtocols = [clientId, '333333']

        // WebSocket
        var socket = new WebSocket('ws://localhost:8000/ws?dev=123456789', subProtocols);
        const attachAddon = new AttachAddon(socket); // 建立websocket链接
        terminal.loadAddon(attachAddon);


        socket.onopen = function() {
			// WebSocket
            // terminal.attach(socket);
			terminal.writeln(termSymbol + '\x1B[0mWelcome to \x1B[1;3;31mXTerm.js !!')
			terminal.write(termSymbol)
        };

        // WebSocket
        socket.onclose = function() {
            terminal.write('\nConnection closed.');
        };

        // WebSocket
        socket.onerror = function(error) {
            terminal.write('\nWebSocket error: ' + error.message);
        };

		socket.onmessage = function(event) {
			console.log("websocket接收数据: " + event.data);
			terminal.writeln(event.data);
            terminal.write(termSymbol)
		};


		var inputBuffer = ''; //
		terminal.onData(data => {
			console.log('\\x' + data.charCodeAt().toString(16))
			if (data === '\r') {
				// terminal.writeln(`\r\nYou typed: ${inputBuffer}`);
			    socket.send(JSON.stringify({"clientId":clientId, "type":'GATE_DEBUG', "data":inputBuffer}))
				inputBuffer = '';
				terminal.writeln('');
			}
			//
			else if (data === '\x7f') { // '\x7f' ASCII
				inputBuffer = inputBuffer.slice(0, -1); //
				terminal.write('\b \b'); //
			}
			//
			else {
				inputBuffer += data; //
				terminal.write(data); //
			}
		});
     
    </script>
</body>
</html>